package com.xpec.c4.game.common;

import java.nio.charset.Charset;


/**
 * 
 *
 */
public class StringHelper {

	// private static final Log log = LogFactory.getLog(StringHelper.class);
	
	/**
	 * 計算字串長度<br>
	 * 英語系字元1Byte, 其他語系字元算2Bytes
	 * 
	 * @param str
	 * @return 返回計算結果單位是byte
	 */
	public static int calcStringLenth(String data) {
		char[] charBuf = data.toCharArray();
		int len = 0;
		int l = 0;
		String cStr = null;
		for (char nc : charBuf) {
			cStr = String.valueOf(nc);
			l = cStr.getBytes(Charset.forName("utf-8")).length;
			if (l > 1) {
				len += 2;
			} else if (l == 1) {
				len += 1;
			}
		}
		return len;
	}
	
	public static boolean hasInvalidUTF8Code(String name) {
		return hasInvalidUTF8Code(name, true);
	}
	
	/**
	 * 是否有不支援的utf8字元
	 * @param name
	 * @return
	 */
	public static boolean hasInvalidUTF8Code(String name, boolean filterWhiteSpace) {
		int length = name.length();
		for (int offset = 0; offset < length;)
		{
			int codePoint = name.codePointAt(offset);

			// 擋掉不合法字
			if(Character.isSupplementaryCodePoint(codePoint))
			{
				return true;
			}

			if(filterWhiteSpace)
			{
				// 擋掉空白字
				if(Character.isWhitespace(codePoint))
				{
					return true;
				}

				// 這個也是空白字
				// isWhitespace 不擋 nbsp(0xa0, 0x2007, 0x202f)
				// zwsp也擋掉(0x200b)

				if(codePoint == 0xa0 || codePoint == 0x2007 || codePoint == 0x202f || codePoint == 0x200b)
				{
					return true;
				}
			}

			offset += Character.charCount(codePoint);
		}
		
		//舊的檢查，先留著吧
		char[] nameChars = name.toCharArray() ;
        for (char nc : nameChars) {
        	if( nc >= Character.MIN_SURROGATE && nc < (Character.MAX_SURROGATE + 1)){
        		return true;
        	}
//        	if(Character.isSurrogate(nc)){
//        		return true;
//        	}

//           String cStr = String.valueOf(nc);
//           byte [] tmpB = cStr.getBytes( Charset.forName("utf-8")) ;             
//           // 大於0xFF 必須要能正確轉出2Bytes以上的編碼
//           if((( int) nc) >= 256 && tmpB .length < 2 ){
//                return true ;
//           }
        }
        return false ;		
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public static String toValidUTF8String(String name) {
		StringBuilder strBuf = new StringBuilder();
		char[] nameChars = name.toCharArray();
		for (char nc : nameChars) {
			if( nc >= Character.MIN_SURROGATE && nc < (Character.MAX_SURROGATE + 1)){
				strBuf.append('?');
			} else {
				strBuf.append(nc);
			}
		}
		return strBuf.toString();
	}
	
}
